package com.yzc.mihuyou.configurer;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.yzc.mihuyou.entity.MessageBody;
import com.yzc.mihuyou.service.UserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.EOFException;
import java.io.IOException;
import java.lang.annotation.Documented;
import java.util.*;

@Component
@Slf4j
@ServerEndpoint("/socket/{name}")
public class WebChatSocket {

    private  StringRedisTemplate stringRedisTemplate = SpringUtil.getBean(StringRedisTemplate.class);

    @OnOpen
    public void onOpen(@PathParam("name") String name, Session session) throws IOException {
//        System.out.println(SocketStorage.sessionMap.putIfAbsent(name, session));
        if (SocketStorage.sessionMap.putIfAbsent(name, session) != null){
            throw new RuntimeException("用户名已存在，请更换用户名。");
        }
        SocketStorage.nameMap.put(session.getId(), name);
//        MessageBody systemMessage = new MessageBody();
//        systemMessage.setContent(name + "成功建立连接");
//        systemMessage.setFromName("system");
//        session.getBasicRemote().sendText(JSONObject.toJSONString(systemMessage));
    }

    @OnClose
    public void onClose(Session session){
        System.out.println(session.getId()+"az");
        System.out.println(SocketStorage.nameMap);
        String name = SocketStorage.nameMap.remove(session.getId());
        System.out.println(name);
//        已下线
        System.out.println(SocketStorage.sessionMap);
        SocketStorage.sessionMap.remove(name);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("监听到消息：{}", message);
        MessageBody messageBody = JSONObject.parseObject(message, MessageBody.class);
        if (messageBody == null){
            return;
        }
        messageBody.setSendTime(new Date());

        String key=messageBody.getFromName()+","+messageBody.getToName();

        if(!stringRedisTemplate.opsForHash().hasKey("userIDs", key)){
             key=messageBody.getToName()+","+messageBody.getFromName();
            if(!stringRedisTemplate.opsForHash().hasKey("userIDs", key)){
                key=null;
            }
        }

        List<MessageBody> list=new ArrayList<>();
        if(key!=null){
            try {
                String sjw= (String) stringRedisTemplate.opsForHash().get("userIDs",key);
                System.out.println(sjw);
                list= JSONObject.parseArray(sjw,MessageBody.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            key=messageBody.getFromName()+","+messageBody.getToName();
        }
        list.add(list.size(),messageBody);
        if(!messageBody.getContent().equals("")){
            try {
                String typeListJson = JSONUtil.toJsonStr(list);
                stringRedisTemplate.opsForHash().put("userIDs", key,typeListJson);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String fromUser = SocketStorage.nameMap.get(session.getId());
        //设置发消息的人
        messageBody.setFromName(fromUser);
        System.out.println(list);
        //将消息转发给收消息的人
        Session toSession = SocketStorage.sessionMap.get(messageBody.getToName());
        System.out.println(toSession);
        if (toSession != null){
            Map<String,Object> map=new HashMap<>();
            map.put("liaoNme",list);
            map.put("messageBody",messageBody);
            try {
                toSession.getBasicRemote().sendText(JSONObject.toJSONString(map));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error){
//        if (error instanceof EOFException && error.getMessage() == null){
//            String name = SocketStorage.nameMap.get(session.getId());
//            SocketStorage.nameMap.remove(session.getId());
//            SocketStorage.sessionMap.remove(name);
//            log.info("{}长时间没有活动，连接已断开", name);
//        }
    }

}
